package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.BuildConfig;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.utils.SPUtils;
import com.longqinuo.mycarservice.utils.VerificationUtils;


import org.json.JSONException;
import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LoginFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LoginFragment extends Fragment implements View.OnClickListener {
    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    private String mPhoneNumber;
    private String mPassword;
    private RequestQueue queue;
    private String url;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ImageView iv_login_close;
    private EditText et_phone_number;
    private EditText et_pass_word;
    private TextView tv_forget_password;
    private TextView tv_just_register;
    private Button btn_login;

    public LoginFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LoginFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        queue = Volley.newRequestQueue(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        initView(view);
        return view;
    }
    public boolean hasValue() {
        if (TextUtils.isEmpty(mParam1)||TextUtils.isEmpty(mParam2)) {
            return false;
        }
        return true;
    }

    private void initView(View view) {
        manager = getActivity().getSupportFragmentManager();
        iv_login_close = (ImageView) view.findViewById(R.id.iv_login_close);
        iv_login_close.setOnClickListener(this);
        et_phone_number = (EditText) view.findViewById(R.id.et_phone_number_login);
        et_pass_word = (EditText) view.findViewById(R.id.et_pass_word_login);
        tv_forget_password = (TextView) view.findViewById(R.id.tv_forget_password);
        tv_forget_password.setOnClickListener(this);
        tv_just_register = (TextView) view.findViewById(R.id.tv_just_register);
        tv_just_register.setOnClickListener(this);
        btn_login = (Button) view.findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
        if (hasValue()) {
            et_phone_number.setText(mParam1);
            et_pass_word.setText(mParam2);
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        mTransaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.iv_login_close:
                manager.popBackStack();
                break;
            case R.id.tv_forget_password:
                mTransaction.replace(R.id.ll_main_layout,new FindPasswordFragment(),"FindPassword");
                mTransaction.addToBackStack("FindPassword");
                mTransaction.commit();
                break;
            case R.id.tv_just_register:
                mTransaction.replace(R.id.ll_main_layout,new JustRegisterFragment(),"JustRegister");
                mTransaction.addToBackStack("JustRegister");
                mTransaction.commit();
                break;
            case R.id.btn_login:
                doLogin();
                break;
        }

    }
    public void doLogin() {  //点击登陆按钮 执行登陆

        if (submit()) {
            url = PathUtils.LOGIN_URL + "?phone=" + mPhoneNumber + "&password=" + mPassword;
            JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    if (BuildConfig.DEBUG) Log.d(">>>onResponse", jsonObject.toString());
                    try {
                        int code = jsonObject.getInt("code");
                        switch (code) {
                            case 0:
                                loginSuccess(jsonObject);
                                break;
                            case -1:
                                String error = jsonObject.getString("errorMessage");
                                Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    if (BuildConfig.DEBUG) Log.d(">>>>>", "登录响应失败");
                }
            });
            queue.add(request);

        }
    }
    public void loginSuccess(JSONObject jsonObject) throws JSONException {   //执行登录请求  的成功处理
        JSONObject data = jsonObject.getJSONObject("data");
        Log.d("LoginFragment", ">>>>"+data.toString());
        String phone = data.getString("phone");
        int pwd = data.getInt("password");
        int id = data.getInt("id");
        String name = data.getString("userName");
        String headPic = data.getString("headPic");

        SPUtils.setSP(getActivity(), "userPhone", phone);
        SPUtils.setSP(getActivity(), "userPwd", pwd);
        SPUtils.setSP(getActivity(), "userId", id);
        SPUtils.setSP(getActivity(),  "userName", name);
        SPUtils.setSP(getActivity(),"headerPath",headPic);
        Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();

        SPUtils.setSP(getActivity(),"isLogin",true);
        PathUtils.havedLogin = true;
        String header = (String) SPUtils.getSp(getActivity(),"headerPath","");

        String headerUrl = PathUtils.LOAD_HEADER+header;
        UserFragment.setUserName(mPhoneNumber);
        UserFragment.setUserHeader(headerUrl);

        LoginFragment loginFragment = (LoginFragment) manager.findFragmentByTag("Login");
        if (loginFragment!=null)
            mTransaction.detach(loginFragment);
        mTransaction.commit();

    }

    private boolean submit() {
        // validate
        mPhoneNumber = et_phone_number.getText().toString().trim();
        if (TextUtils.isEmpty(mPhoneNumber)) {
            Toast.makeText(getContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!VerificationUtils.matcherPhoneNum(mPhoneNumber)) {
            Toast.makeText(getActivity(), "手机号码格式不正确", Toast.LENGTH_SHORT).show();
        }
        mPassword = et_pass_word.getText().toString().trim();
        if (TextUtils.isEmpty(mPassword)) {
            Toast.makeText(getContext(), "请输入密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;

        // TODO validate success, do something


    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
